package com.jiuye.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiuye.common.CustomException;
import com.jiuye.common.GlobalConstant;
import com.jiuye.common.R;
import com.jiuye.entity.Category;
import com.jiuye.entity.Dish;
import com.jiuye.entity.DishDto;
import com.jiuye.entity.DishFlavor;
import com.jiuye.service.ICategoryService;
import com.jiuye.service.IDishFlavorService;
import com.jiuye.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 新增菜品表示层
 *
 * @author likeWen
 * @since 2022/11/4 15:51
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private IDishService dishService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    /**
     * 更新菜品数据
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dto){
        this.dishService.updateWithFlavor(dto);
        //清理所有菜品的缓存数据
        //获取所有以dish:XXX开头的key
        Set keys = redisTemplate.keys("dish:*");
        redisTemplate.delete(keys);//删除这些key
        return R.success(GlobalConstant.SUCCESS);
    }

    /**
     * 根据id查询数据
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id){
        //两个表，自定义方法getByIdWithFlavor
        DishDto dishDto = this.dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    /**
     * 分页查询
     */
    @GetMapping("/page")
    @Transactional//开启事务
    public R<Page<DishDto>> getPage(Integer page,Integer pageSize,String name ){
        //1.构造分页对象
        Page<Dish> queryPage = new Page<>(page, pageSize);
        //2.构建查询及排序条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //name查询
        queryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
        //根据修改时间倒序
        //用户体验方面更好
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //3.执行分页条件查询
        Page<Dish> dishPage = this.dishService.page(queryPage, queryWrapper);
        //4.构建返回结果对象，并copy查询结果到该对象中
        Page<DishDto> result = new Page<>();
        BeanUtils.copyProperties(dishPage,result,"records");
        //5.遍历分页查询列表数据 把Dish对象转为DishDto对象，同时赋值分类名称
        //这里存放的所有我们要返回的数据
        List<DishDto> records = new ArrayList<>();
        for (Dish dish : dishPage.getRecords()) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            //查询分类
            Category category = this.categoryService.getById(dish.getCategoryId());
            if (category != null){
                //给分类名称赋值
                dishDto.setCategoryName(category.getName());
            }
            records.add(dishDto);
        }
        //6.封装数据并返回
        result.setRecords(records);
        return R.success(result);
    }
    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        //清楚所有菜品的缓存，保证缓存与数据库的一致性
        //Set keys = redisTemplate.keys("dish:*");
        //redisTemplate.delete(keys);
        //清理某个分类下的菜品缓存数据
        String key = "dish:"+dishDto.getCategoryId()+":"+dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success(GlobalConstant.SUCCESS);
    }
    /**
     *根据菜品起售状态查询
     */
/*    @GetMapping("/list")
    public R<List<Dish>> getList(Dish dish){
        //判断如果没有传出参数的话，抛出异常
        if (null == dish){
            throw  new CustomException("菜品查询失败");
        }
        //根据菜品分类id查询
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //菜品分类
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //查询起售状态：1：起售，0：停售
        queryWrapper.eq(Dish::getStatus,1);
        List<Dish> list = this.dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //从缓存中读取列表数据
        List<DishDto> dishDtoList;
        String key = "dish:"+dish.getCategoryId()+":"+dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtoList != null){
            return R.success(dishDtoList);
        }
        dishDtoList = new ArrayList<>();
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        //region foreach写法
        //List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish item : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }
        //endregion
        //region Lambda使用Map方法的写法
        //        List<DishDto> dishDtoList = list.stream().map((item) -> {
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item,dishDto);
//            Long categoryId = item.getCategoryId();//分类id
//            //根据id查询分类对象
//            Category category = categoryService.getById(categoryId);
//            if(category != null){
//                String categoryName = category.getName();
//                dishDto.setCategoryName(categoryName);
//            }
//            //当前菜品的id
//            Long dishId = item.getId();
//            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
//            //SQL:select * from dish_flavor where dish_id = ?
//            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
//            dishDto.setFlavors(dishFlavorList);
//            return dishDto;
//        }).collect(Collectors.toList());
        //endregion
        //存入redis
        //设置时间是保底操作
        //有可能会出现预期之外的bug导致缓存与数据库的一致性出现问题
        //设置时间后，到时缓存自动删除，重新读取数据库
        redisTemplate.opsForValue().set(key, dishDtoList, 60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
